<template>
  <div class="app-container calendar-list-container">
    <div class="apply-query">
      <el-row class="filter-query">
        <el-col><i class="el-icon-search"/>&nbsp;&nbsp;筛选查询</el-col>
      </el-row>

      <el-form>
        <el-row>
          <el-col style="margin-bottom: 20px;margin-top: 20px;margin-left: 30px">
            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="姓名或账户"
                      v-model="listQuery.name" clearable>
            </el-input>

            <el-select v-model="listQuery.groupType" placeholder="角色类型" :clearable="true" style="width: 200px"
                       @keyup.enter.native="handleFilter">
              <el-option v-for="item in groupTypeList" :key="item.value" :label="item.label" :value="item.value">
                <span>{{ item.label }}</span>
              </el-option>
            </el-select>
            <el-select v-model="listQuery.isDisabled" placeholder="是否禁用" :clearable="true" style="width: 200px"
                       @keyup.enter.native="handleFilter">
              <el-option v-for="item in disabledList" :key="item.value" :label="item.label" :value="item.value">
                <span>{{ item.label }}</span>
              </el-option>
            </el-select>
            <el-button class="filter-item" type="primary" icon="search" @click="handleFilter" style="margin-left: 10%">
              搜索
            </el-button>
            <el-button type="primary" @click="reset">重置</el-button>
            <el-button class="filter-item" v-if="userManager_btn_add" style="margin-left: 10px;" @click="handleCreate"
                       type="primary"
                       icon="edit">添加
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="data-list">
      <el-row class="list-content">
        <el-col :span="1" style="text-align: center">
          <svg-icon icon-class="chart"/>
        </el-col>
        <el-col :span="2">数据列表</el-col>
      </el-row>
      <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row>
        <el-table-column align="center" label="姓名">
          <template slot-scope="scope">
            <span>{{scope.row.name}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="账户">
          <template slot-scope="scope">
            <span>{{scope.row.username}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="联系电话">
          <template slot-scope="scope">
            <span>{{scope.row.mobilePhone}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="角色" prop="groupType" :formatter="formatter.groupTypeFormatter">
        </el-table-column>
        <el-table-column align="center" label="邮箱">
          <template slot-scope="scope">
            <span>{{scope.row.email}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="签名">
          <template slot-scope="scope">
            <viewer>
              <img style="width: 60px;heighViewert: 60px"
                   :src="scope.row.description">
            </viewer>
          </template>
        </el-table-column>

        <el-table-column align="center" label="是否禁用">
          <template slot-scope="scope">
            <span>{{scope.row.isDisabled === '1'?'是':'否'}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建时间">
          <template slot-scope="scope">
            <span>{{scope.row.createTime | cutTime}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="300">
          <template slot-scope="scope">
            <el-button v-if="userManager_btn_edit" size="small" type="success" @click="handleUpdate(scope.row)">编辑
            </el-button>
            <el-button size="small" type="warning" v-if="scope.row.isDisabled === '0'"
                       @click="handDisabledUser(scope.row,'1')">禁用
            </el-button>
            <el-button size="small" type="warning" v-if="scope.row.isDisabled === '1'"
                       @click="handDisabledUser(scope.row,'0')">启用
            </el-button>
            <el-button v-if="userManager_btn_del" size="small" type="danger" @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.page"
                     :page-sizes="[10, 20, 30, 50, 100, 200]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名"
                    onkeypress="javascript:if(event.keyCode == 32)event.returnValue = false"></el-input>
        </el-form-item>
        <el-form-item label="账户" prop="username">
          <el-input v-if="dialogStatus == 'create'" v-model="form.username" placeholder="请输入账户">
            <template slot="prepend"></template>
          </el-input>
          <el-input v-else v-model="form.username" placeholder="请输入账户" readonly>
          </el-input>
        </el-form-item>
        <el-form-item v-if="dialogStatus == 'create'" label="密码" placeholder="请输入密码" prop="password">
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select class="filter-item" v-model="form.sex" placeholder="请选择">
            <el-option v-for="item in  sexOptions" :key="item.id" :label="item.labelDefault"
                       :value="item.labelDefault"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="form.mobilePhone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-radio-group v-model="form.groupType" v-if="form.groupType!=='tenement' ">
            <el-radio label="commonAdmin">管理员</el-radio>
            <el-radio label="collectPersonnel">采集员</el-radio>
            <el-radio label="checkPersonnel">排查员</el-radio>
            <el-radio label="supervisor">监理员</el-radio>
            <el-radio label="firstParty">甲方</el-radio>
            <el-radio label="service">客服</el-radio>
            <el-radio label="tenement">商户</el-radio>
          </el-radio-group>

          <el-input value="商户" v-else :disabled="flag"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" v-if="form.groupType === 'checkPersonnel'">
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="签名图片" v-if="form.groupType === 'checkPersonnel'">
          <el-upload ref="picture"
                     action="api/oss/upload"
                     :headers="uploadHeaders"
                     list-type="picture-card"
                     :file-list="appearanceImageList"
                     :on-success="handleUploadSuccess('appearance')"
                     :on-remove="handleRemove('appearance')"
                     :limit=1
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择部门" width="30%" :visible.sync="dialogDepartVisible">
      <depart-selector @closeDepartDialog="closeDepartDialog" ref="departSelector"></depart-selector>
      <span slot="footer" class="dialog-footer">
        <el-button class="filter-item" style="margin-left: 10px;" @click="handlerAddDepart" type="primary" icon="edit">添加</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    page,
    addObj,
    getObj,
    delObj,
    putObj,
    disabledUser
  } from '@/api/admin/user/index';

  import formatter from '@/utils/formatter'
  import { getTypeValue } from '@/api/dict/dictValue/index';
  import { mapGetters } from 'vuex';
  import { getToken } from '@/utils/auth'

  export default {
    name: 'user',
    components: {
      'depart-selector': () => import('./components/departSelector')
    },
    data() {
      return {
        formatter,
        flag: true,
        uploadHeaders: {
          Authorization: null
        },
        appearanceImageList: [],
        form: {
          username: undefined,
          name: undefined,
          sex: 'comm_sex_man',
          password: undefined,
          description: undefined,
          departName: undefined,
          departId: undefined,
          groupType: undefined,
          email: undefined
        },
        groupTypeList: [{
          value: 'tenement',
          label: '商户'
        }, {
          value: 'collectPersonnel',
          label: '采集员'
        }, {
          value: 'superAdmin',
          label: '超级管理员'
        }, {
          value: 'firstParty',
          label: '甲方'
        }, {
          value: 'projectAdmin',
          label: '项目管理员'
        }, {
          value: 'checkPersonnel',
          label: '排查员'
        }, {
          value: 'supervisor',
          label: '监理员'
        }],
        disabledList: [{
          value: '1',
          label: '是'
        }, {
          value: '0',
          label: '否'
        }],
        rules: {
          name: [
            {
              required: true,
              message: '请输入用户',
              trigger: 'blur'
            }
          ],
          username: [
            {
              required: true,
              message: '请输入账户',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 20,
              message: '长度在 3 到 20 个字符',
              trigger: 'blur'
            }
          ],
          password: [
            {
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 5,
              max: 20,
              message: '长度在 5 到 20 个字符',
              trigger: 'blur'
            }
          ]
        },
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          name: undefined,
          username: undefined
        },
        sexOptions: [],
        dialogFormVisible: false,
        dialogDepartVisible: false,
        dialogStatus: '',
        userManager_btn_edit: false,
        userManager_btn_del: false,
        userManager_btn_add: false,
        textMap: {
          update: '编辑',
          create: '创建'
        },
        tableKey: 0
      }
    },
    created() {
      this.uploadHeaders.Authorization = getToken()
      this.getQuery()
      this.getList();
      this.userManager_btn_edit = this.elements['userManager:btn_edit'];
      this.userManager_btn_del = this.elements['userManager:btn_del'];
      this.userManager_btn_add = this.elements['userManager:btn_add'];
      getTypeValue('comm_sex').then(response => {
        this.sexOptions = response.data.rows;
      });
    },
    activated() {
      this.getQuery()
    },
    computed: {
      ...mapGetters([
        'elements'
      ])
    },
    methods: {
      getQuery() {
        const searchAdminUser = window.sessionStorage.getItem('searchAdminUser')
        if (searchAdminUser) {
          this.listQuery = JSON.parse(searchAdminUser)
        }
      },
      getList() {
        this.listLoading = true;
        this.listQuery.username = this.listQuery.name;
        page(this.listQuery)
          .then(response => {
            this.list = response.data.rows;
            this.total = response.data.total;
            this.listLoading = false;
          })
      },
      handleFilter() {
        this.getList();
      },
      reset() {
        this.listQuery = {}
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      handleCreate() {
        this.resetTemp();
        this.dialogStatus = 'create';
        this.dialogFormVisible = true;
      },
      handleUpdate(row) {
        getObj(row.id)
          .then(response => {
            this.appearanceImageList = [];
            this.form = response.data;
            if (response.data && response.data.description) {
              this.appearanceImageList.push({ name: 'a', url: response.data.description })
            }
            try {
              const depart = JSON.parse(response.data.departId)
              if (typeof depart === 'object' && depart) {
                this.form.departName = depart.name
                this.form.departId = depart.id
              } else {
                this.form.departId = response.data.departId
                this.form.departName = response.data.departId
              }
            } catch (e) {
              console.error(e)
            }
            this.dialogFormVisible = true;
            this.dialogStatus = 'update';
          });
      },
      handleUploadSuccess() {
        // 这里才是真正的钩子
        return (response, file, fileList) => {
          const list = []
          for (const f of fileList) {
            if (f.response) {
              list.push(f.response.data)
            } else {
              list.push(f.url)
            }
          }
          this.form.description = list.toString();
        }
      },
      // 上传图片
      handleRemove() {
        return (file, fileList) => {
          const list = []
          for (const f of fileList) {
            if (f.response) {
              list.push(f.response.data)
            } else {
              list.push(f.url)
            }
          }
          this.form.description = list.toString();
        }
      },
      handleDelete(row) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            delObj(row.id)
              .then(() => {
                this.$notify({
                  title: '成功',
                  message: '删除成功',
                  type: 'success',
                  duration: 2000
                });
                const index = this.list.indexOf(row);
                this.list.splice(index, 1);
              });
          });
      },
      handDisabledUser(row, type) {
        let title = ''
        if (type === '1') {
          title = '是否禁用掉该用户?'
        } else {
          title = '是否启用该用户?'
        }
        this.$confirm(title, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            disabledUser(row.id, type)
              .then(() => {
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000
                });
                const index = this.list.indexOf(row);
                this.list.splice(index, 1);
              });
          });
      },
      handlerAddDepart() {
        this.$refs.departSelector.onSubmit()
      },
      create(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            addObj(this.form)
              .then(() => {
                this.dialogFormVisible = false;
                this.getList();
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                });
              })
          } else {
            return false;
          }
        });
      },
      cancel(formName) {
        this.dialogFormVisible = false;
        this.$refs[formName].resetFields();
      },
      update(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            this.dialogFormVisible = false;
            this.form.password = undefined;
            putObj(this.form.id, this.form).then(() => {
              this.dialogFormVisible = false;
              this.getList();
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              });
            });
          } else {
            return false;
          }
        });
      },
      openDepartDialog() {
        this.dialogDepartVisible = true
      },
      closeDepartDialog(depart) {
        this.form.departName = depart.label
        this.form.departId = depart.id
        this.dialogDepartVisible = false
      },
      resetTemp() {
        this.form = {
          username: undefined,
          name: undefined,
          sex: '男',
          password: undefined,
          description: undefined,
          departId: undefined,
          departName: undefined,
          email: undefined
        };
      }
    },
    beforeDestroy() {
      window.sessionStorage.setItem('searchAdminUser', JSON.stringify(this.listQuery))
    }
  }
</script>
